﻿/*
 *   Copyright 2011 Peter Crossley
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 *  ----------------------------------------------------------------------------
 *  File:       CloudSettings.cs
 *  Author:     Peter Crossley
 *  ----------------------------------------------------------------------------
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UEC.Modules.Basic;
using Microsoft.Win32;
using System.IO;

namespace UEC.ConfigUI
{
    public partial class CloudSettings : UserControl
    {
        private CloudManager manager;
        private string CLOUD_SETTINGS = "CloudSettings";
        public CloudSettings(CloudManager manager)
        {
            this.manager = manager;
            manager.SaveSettingsEvent += new CloudManager.SaveSettingsHandler(SaveSettings);
            manager.LoadSettingsEvent += new CloudManager.LoadSettingsHandler(LoadSettings);

            InitializeComponent();
            LoadSettings();
            this.txtMetaDataUrl.TextChanged += new System.EventHandler(manager.SettingsChanged);
            this.txtUserDataUrl.TextChanged += new System.EventHandler(manager.SettingsChanged);
            this.cbxComPort.SelectedIndexChanged += new System.EventHandler(manager.SettingsChanged);
        }

        private void LoadSettings(object sender=null, CloudManager.LoadEventArgs e=null)
        {
            if (e != null)
            {
                if (e.Reset)
                {
                    manager.DeleteKeyStore(CLOUD_SETTINGS);
                }
            }
            cbxComPort.SelectedIndex = Int32.Parse(manager.GetValue(CLOUD_SETTINGS, "ComPortIndex", Properties.Settings.Default.ComPortIndex).ToString());
            txtMetaDataUrl.Text = (string)manager.GetValue(BasicService.BASIC_SETTINGS, "MetaDataUrl", Properties.Settings.Default.MetaDataUrl);
            txtUserDataUrl.Text = (string)manager.GetValue(BasicService.BASIC_SETTINGS, "UserDataUrl", Properties.Settings.Default.UserDataUrl);
            chkDebug.Checked = manager.Debug;

            if (!manager.GetValueAsBoolean("Service", "ServiceInstalled", Properties.Settings.Default.ServiceInstalled))
            {
                btnService.Text = Properties.Resources.uiInstallService;
            }
            else
            {
                btnService.Text = Properties.Resources.uiUnInstallService;
            }
        }

        public void SaveSettings(object sender, EventArgs e)
        {
            manager.SetValue(BasicService.BASIC_SETTINGS, "MetaDataUrl", txtMetaDataUrl.Text);
            manager.SetValue(BasicService.BASIC_SETTINGS, "UserDataUrl", txtUserDataUrl.Text);
            manager.SetValue(CLOUD_SETTINGS, "ComPortIndex", cbxComPort.SelectedIndex);
            manager.SetValue(CLOUD_SETTINGS, "ComPort", cbxComPort.SelectedItem.ToString());
            manager.Debug = chkDebug.Checked;
        }

        private void btnInstallService_Click(object sender, EventArgs e)
        {
            if (!manager.GetValueAsBoolean("Service", "ServiceInstalled", Properties.Settings.Default.ServiceInstalled))
            {
                InstallService();
                btnService.Text = Properties.Resources.uiUnInstallService;
            }
            else
            {
                UnInstallService();
                btnService.Text = Properties.Resources.uiInstallService;
            }

        }

        private void btnRunNow_Click(object sender, EventArgs e)
        {
            manager.OnSaveSettings();
            manager.OnCloudServiceRun();
            manager.OnLoadSettings(false);
            if (manager.Reboot)
            {
                DialogResult r = MessageBox.Show(Properties.Resources.uiSystemReboot, Properties.Resources.uiSystemRebootTitle, MessageBoxButtons.YesNo);
                if (r == DialogResult.Yes)
                {
                    manager.OnCloudServiceSystemReboot();
                }
            }
            else
            {
                MessageBox.Show(Properties.Resources.uiRunDone, Properties.Resources.uiTitle);
            }
        }

        private void InstallService()
        {
            if (!manager.GetValueAsBoolean("Service", "ServiceInstalled", Properties.Settings.Default.ServiceInstalled))
            {
                manager.OnCloudServiceInstall();
                UEC.Support.ServiceInstaller serviceInstaller = new UEC.Support.ServiceInstaller();
                
                manager.SetValue("Service", "FirstRun", true);
                bool started = serviceInstaller.InstallService(Application.ExecutablePath + " /service", Properties.Resources.ServiceName, Properties.Resources.ServiceTitle, "Appinfo");
                manager.SetValue("Service", "ServiceInstalled", true);

                //add to run on login
                RegistryKey regkey = Registry.Users.CreateSubKey(".DEFAULT\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                regkey.DeleteSubKey(Properties.Resources.ServiceName, false);
                regkey.SetValue(Properties.Resources.ServiceName, Application.ExecutablePath + " /user");

                manager.OnCloudServiceChange();
            }
        }

        private void UnInstallService()
        {
            if (manager.GetValueAsBoolean("Service", "ServiceInstalled", Properties.Settings.Default.ServiceInstalled))
            {
                manager.OnCloudServiceUnInstall();
                UEC.Support.ServiceInstaller serviceInstaller = new Support.ServiceInstaller();
                bool stopped = serviceInstaller.UnInstallService(Properties.Resources.ServiceName);
                
                //add to run on login
                RegistryKey regkey = Registry.Users.CreateSubKey(".DEFAULT\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                regkey.DeleteSubKey(Properties.Resources.ServiceName, false);

                manager.SetValue("Service", "ServiceInstalled", false);
                manager.OnCloudServiceChange();
            }
        }
    }
}
